package com.hp.easyBuy.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.easyBuy.utils.R;
import com.hp.easyBuy.utils.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//扫描controller包中带有注解@RestController的类，处理该类中返回json的所有方法，给返回结果加上统一响应体进行处理后响应给客户端
@RestControllerAdvice(basePackages = "com.hp.easyBuy.controller")
public class ResultAdvice implements ResponseBodyAdvice {
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;   //返回true执行下面方法，返回false不执行
    }

    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        System.out.println(o);
        if (o instanceof R){
            return o;
        }else if (o instanceof String){
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                R r = R.success();
                String result = objectMapper.writeValueAsString(r);
                return result;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else if (o == null){
            R r = R.error();
            return r;
        }
        return R.success(o);
    }
}
